import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/message/viewmodels/video_call_viewmodel.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/utils/flash_notifier.dart';

/// 视频通话视图
/// 显示视频通话界面
class VideoCallView extends StatelessWidget {
  final String otherUserId;

  const VideoCallView({super.key, required this.otherUserId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<VideoCallViewModel>.reactive(
      viewModelBuilder: () {
        final viewModel = VideoCallViewModel(
          getIt.get<AuthFocus>(),
          getIt.get<DialogLens>(),
          otherUserId,
        );
        // 设置自动挂断回调
        viewModel.onAutoHangup = () {
          FlashNotifier.flashInfo('No response from user');
          if (context.mounted) {
            Navigator.of(context).pop();
          }
        };
        viewModel.initialize();
        return viewModel;
      },
      onDispose: (viewModel) {
        // 页面销毁时检查是否需要发送拨打失败消息
        if (!viewModel.isManualHangup) {
          // 自动挂断的情况，已经在定时器中处理
        }
      },
      builder: (context, viewModel, child) {
        if (viewModel.otherUser == null) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        return Scaffold(
          body: Stack(
            children: [
              // 背景：对方的头像
              _buildBackground(viewModel),
              // 黑色半透明蒙层
              ClipRRect(
                borderRadius: BorderRadius.circular(20.r),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                  child: Container(color: Colors.black.withOpacity(0.6)),
                ),
              ),
              // 内容
              SafeArea(
                child: Column(
                  children: [
                    Expanded(
                      child: Center(
                        child: _buildMainContent(context, viewModel),
                      ),
                    ),
                    // 挂断按钮
                    _buildHangupButton(context, viewModel),
                    SizedBox(height: 80.h),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建背景
  Widget _buildBackground(VideoCallViewModel viewModel) {
    if (viewModel.otherUser?.avatar == null) {
      return Container(color: Colors.grey[900]);
    }

    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(viewModel.otherUser!.avatar!),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  /// 构建主要内容
  Widget _buildMainContent(BuildContext context, VideoCallViewModel viewModel) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 对方头像
        Container(
          width: 120.w,
          height: 120.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 20.w,
                offset: Offset(0, 10.h),
              ),
            ],
          ),
          child: CircleAvatar(
            radius: 57.r,
            backgroundColor: Colors.white,
            backgroundImage:
                viewModel.otherUser?.avatar != null
                    ? AssetImage(viewModel.otherUser!.avatar!)
                    : null,
            child:
                viewModel.otherUser?.avatar == null
                    ? Icon(Icons.person, size: 60.w, color: Colors.grey)
                    : null,
          ),
        ),
        SizedBox(height: 40.h),
        // 等待提示文字（带动态点）
        Text(
          'Waiting to accept invitation${'.' * viewModel.dotCount}',
          style: TextStyle(
            fontSize: 16.sp,
            fontFamily:
                GoogleFonts.notoSans(fontWeight: FontWeight.w400).fontFamily,
            color: Colors.white,
          ),
        ),
      ],
    );
  }

  /// 构建挂断按钮
  Widget _buildHangupButton(
    BuildContext context,
    VideoCallViewModel viewModel,
  ) {
    return GestureDetector(
      onTap: () async {
        // 手动挂断
        await viewModel.hangup();
        // 显示取消提示
        FlashNotifier.flashInfo('Call cancelled');
        if (context.mounted) {
          Navigator.of(context).pop();
        }
      },
      child: Container(
        width: 60.w,
        height: 60.w,
        decoration: BoxDecoration(shape: BoxShape.circle),
        padding: EdgeInsets.all(0.w),
        child: Image.asset('assets/images/hand_off.png', fit: BoxFit.contain),
      ),
    );
  }
}
